<?php
/**
 * Created by PhpStorm.
 * User: huynguyen
 * Date: 9/19/14
 * Time: 9:28 PM
 */

namespace Backend\Modules\Video\Controllers;

use Common\library\Common;
use Library\Constant\Constant;
use Library\Utils\Slug;
//use \Phalcon\Paginator\Adapter\Model as Paginator;
use Phalcon\Paginator\Adapter\QueryBuilder as Paginator;
use Phalcon\Mvc\Model\Resultset;
use Library\Pagination\Pager as Pager;
use Backend\Modules\Video\Models\Video;
use Backend\Modules\Video\Models\VideoDescription;
use Backend\Modules\Video\Models\VideoCategoryLink;
use Backend\Modules\Video\Models\Artist;
use Backend\Modules\Video\Models\VideoArtistLink;
use Backend\Modules\Video\Models\VideoFile;
use Backend\Modules\Video\Models\VideoFileLink;
use Backend\Modules\Video\Models\VideoGroup;
use Backend\Modules\Video\Models\VideoGroupLink;
use Backend\Modules\Video\Forms\FormCreateVideo;
use Backend\Modules\Video\Forms\FormSearchVideoFile;
use Backend\Modules\Video\Forms\FormSearchArtist;
use Backend\Modules\Video\Forms\FormSeachVideo;

use Library\Upload\UploadFile as UploadFile;
use Phalcon\Mvc\View;
use Phalcon\Http\Response;

class VideoController extends \BackendController
{
    public $urlVideo = 'video';
    public static $ITEM_PER_PAGE = 20;
    public function indexAction()
    {
        $currentPage = abs($this->request->getQuery('page', 'int', 1));

        $formSearchVideo = new FormSeachVideo();
        $formSearchVideo->setAction($this->getBackendUrl() . '/' . $this->urlVideo);
        $video = new Video();
        $videos = $video->queryBuilderSeachVideo($this->request->get());
        $formSearchVideo->bind($this->request->get() , $video);
        if ($currentPage == 0) {
            $currentPage = 1;
        }
        $uri = str_replace('&page=' . $currentPage , '' , $this->request->getURI());        

        $paginator = new Paginator(array(
              "builder" => $videos,
              "limit"=> Constant::ITEM_PER_PAGE_20,
              "page" => $currentPage
          ));

        $pager = new Pager(
            $paginator,
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => $uri . '&page={%page_number}',
            )
        );

        $this->view->formSearchVideo = $formSearchVideo;
        $this->view->pager = $pager;
    }

    public function createAction()
    {
        $uploadFile = new UploadFile();
        //$uploadFile->loadLibraryScript();
        $this->assets
            ->addJs('vendor/backend/js/video/video_category_ajax.js');

        $form = new FormCreateVideo();

        if($this->request->isPost())
        {
            if($form->isValid($this->request->getPost()) != false)
            {
                $video = new Video();
                //$forms->bind($this->request->getPost() , $video);
                $video->assign(array(
                    'imdb' => 0 ,
                    'slug' => Slug::generate($this->request->getPost('name_vn')),
                    'duration'              => $this->request->getPost('duration'),
                    'is_vip' => 'N',
                    'hot_month'             => $this->request->getPost('status' , 'int'),
                    'created_user'          => $this->auth->getUserId(),
                    'published_user'        => 0,
                    'created_time'          => date('Y-m-d h:m:s'),
                    'updated_time'          => date('Y-m-d h:m:s'),
                    'ip_address'            => '0',
                    'status'                => 'W' ,//$this->request->getPost('status'),
                ));
                if($video->save())
                {
                    $videoDescription = new VideoDescription();
                    $videoDescription->assign(array(
                        'video_id'  => $video->getId(),
                        'name'      => $this->request->getPost('name'),
                        'name_vn'      => $this->request->getPost('name_vn'),
                        'short_name'      => $this->request->getPost('short_name'),
                        'national_id'           => $this->request->getPost('national_id'),
                        'year_product'          => $this->request->getPost('year_product'),
                        'year_publish'          => $this->request->getPost('year_publish'),
                        'description'   => $this->request->getPost('description'),
                    ));
                    $videoDescription->save();
                   
                    $videoCategoriesId = $this->request->getPost('category_id');
                    if($videoCategoriesId)
                    {
                        foreach($videoCategoriesId as $videoCategoryId)
                        {
                            $checkCategoryHaveCategoryLink = VideoCategoryLink::find(array(
                                "video_id = " . $video->getId() . " AND category_id = $videoCategoryId"
                            ))->count();

                            if($checkCategoryHaveCategoryLink <= 0){
                                $videoLink = new VideoCategoryLink();
                                $videoLink->assign(array(
                                    'video_id'  => $video->getId(),
                                    'category_id'      => $videoCategoryId,
                                    'position'      => 0,
                                ));
                                $videoLink->save();
                            }
                        }
                    }

                    //Check if the user has uploaded files
                    if ($this->request->hasFiles() == true) {                        
                        //Print the real file names and their sizes
                        $uploadFile->doUpload(array('folder_upload' => 'files' , 'object_id' => $video->getId() , 'image_id' => 0 , 'object_type' => 'video' , 'type' => 'M' , 'position' => 0) , Common::listThumbnailOptionA());
                    }

                    return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideo . '/edit/' . $video->getId() . '?tab=album');
                }
                $this->flash->error($video->getMessages());
            }
        }
        $this->view->form = $form;
    }

    public function editAction($id)
    {
        $uploadFile = new UploadFile();
        //$uploadFile->loadLibraryScript();

        $this->assets
            ->addJs('vendor/backend/js/video/video_category_ajax.js')
            ->addJs('vendor/backend/js/video/video.js')
            ->addJs('vendor/backend/js/video/video_ajax.js');

        $video = Video::findFirstById($id);
        $videoDescription = VideoDescription::find(array(
            "video_id = $id"
        ))->getFirst();

        $videoCategoryLink = VideoCategoryLink::findFirst("video_id = $id");

        //die(print $id);
        if(!$video)
        {
            $this->flash->error("Video was not found");
            return $this->dispatcher->forward(array(
                'action' => 'index'
            ));
        }

        $form = new FormCreateVideo($video , array('name' => 'video' , 'edit' => true));
        $form->setAction($this->getBackendUrl() . '/' . $this->urlVideo . '/edit/' . $id);
        $formDescription = new FormCreateVideo($videoDescription , array('edit' => true));
        //$formCategoryLink = new FormCreateVideo($videoCategoryLink , array('edit' => true));
        $tab = $this->request->get('tab') ? $this->request->get('tab') : 'general';

        if($this->request->getPost())
        {            
            switch($tab)
            {
                case 'general':
                    if($form->isValid($this->request->getPost()) != false)
                    {
                        $video->assign(array(
                            'imdb' => 0 ,
                            //'slug' => Slug::generate($this->request->getPost('name_vn')),
                            'duration'              => $this->request->getPost('duration'),
                            'is_vip' => 'N',//$this->request->getPost('is_vip'),
                            'hot_month'             => $this->request->getPost('status' , 'int'),
                            'created_user'          => 1,//$this->request->getPost('status', 'int'),
                            'published_user'        => 1,//$this->request->getPost('status', 'int'),
                            'created_time'          => date('Y-m-d h:m:s'),
                            'updated_time'          => date('Y-m-d h:m:s'),
                            'ip_address'            => '0',
                            //'status'                => $this->request->getPost('status'),
                        ));

                        if($video->save())
                        {
                            $videoDescription->assign(array(
                                'video_id'  => $video->getId(),
                                'name'      => $this->request->getPost('name'),
                                'name_vn'      => $this->request->getPost('name'),
                                'short_name'      => $this->request->getPost('short_name'),
                                'national_id'           => $this->request->getPost('national_id'),
                                'year_product'          => $this->request->getPost('year_product'),
                                'year_publish'          => $this->request->getPost('year_publish'),
                                'description'   => $this->request->getPost('description'),
                            ));

                            if($videoDescription->update() == false)
                            {
                                $this->flash->error($videoDescription->getMessages());
                            }

                            $videoCategoryLinksDelete = VideoCategoryLink::find(array(
                                "video_id = " . $video->getId()
                            ));
                            if($videoCategoryLinksDelete)
                            {
                                foreach ($videoCategoryLinksDelete as $videoCategoryLinks) {
                                    if($videoCategoryLinks){
                                        $videoCategoryLinks->delete();  
                                    }
                                }
                            }

                            $videoCategoriesId = $this->request->getPost('category_id');
                            
                            if($videoCategoriesId)
                            {
                                try {
                                    foreach($videoCategoriesId as $videoCategoryId)
                                    {
                                        $checkCategoryHaveCategoryLink = VideoCategoryLink::find(array(
                                            "video_id = " . $id . " AND category_id = $videoCategoryId"
                                        ))->count();

                                        if($checkCategoryHaveCategoryLink <= 0){
                                            $videoLink = new VideoCategoryLink();
                                            $videoLink->assign(array(
                                                'video_id'  => $video->getId(),
                                                'category_id'      => $videoCategoryId,
                                                'position'      => 0,
                                            ));
                                            $videoLink->save();
                                        }
                                    }
                                } catch (Exception $e) {
                                   echo $e->getMessage();
                                   echo $e->getTraceAsString();
                                }
                            }

                            if ($this->request->hasFiles() == true) {
                                $uploadFile->doUpload(array('folder_upload' => 'files' , 'object_id' => $video->getId() , 'object_type' => 'video' , 'type' => 'M' , 'position' => 0) , Common::listThumbnailOptionA());
                            }

                            return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideo);
                        }
                        $this->flash->error($video->getMessages());
                    }
                    break;

                case 'album':
                    if ($this->request->hasFiles() == true) {
                        $paramUpload = array(
                            'folder_upload' => 'files' ,
                            'object_id' => $video->getId() ,
                            'object_type' => 'video' ,
                            'type' => 'A' ,
                            'position' => 0
                        );
                        $uploadFile->doUpload($paramUpload , Common::listThumbnailOptionA());
                    }
                    break;
                case 'actor':
                case 'director':
                    if($this->request->isPost() == true)
                    {
                        if($this->request->getPost('selectArtist'))
                        {
                            $selectArtists = $this->request->getPost('selectArtist');

                            $data = array();
                            foreach($selectArtists as $artistId)
                            {
                                $checkActorHaveVideo = VideoArtistLink::find(array(
                                    "video_id = $id AND artist_id = $artistId"
                                ))->count();

                                if($checkActorHaveVideo <= 0)
                                {
                                    $selectArtist = Artist::findFirstById($artistId)->toArray();
                                    if($selectArtist)
                                    {
                                        $videoArtistLink = new VideoArtistLink();
                                        $videoArtistLink->setVideoId($id);
                                        $videoArtistLink->setArtistId($artistId);
                                        if(!$videoArtistLink->save())
                                        {

                                        }
                                    }
                                }
                            }
                        }

                        if($this->request->getPost('selectArtistRemove'))
                        {
                            $selectedArtists = $this->request->getPost('selectArtistRemove');

                            foreach($selectedArtists as $artistId)
                            {
                                $videoArtistLink = VideoArtistLink::find(array(
                                    "video_id = $id AND artist_id = $artistId",
                                ))->getFirst();

                                if($videoArtistLink)
                                {
                                    if(!$videoArtistLink->delete())
                                    {

                                    }
                                }
                            }
                        }
                    }
                    break;

                case 'group':

                    if($this->request->getPost('selectedVideoGroupRemove'))
                    {
                        $selectedVideoGroupLink = $this->request->getPost('selectedVideoGroupRemove');

                        foreach($selectedVideoGroupLink as $videoGroupId)
                        {
                            $videoGroupLink = VideoGroupLink::find(array(
                                "video_id = $id AND video_group_id = $videoGroupId",
                            ))->getFirst();

                            if($videoGroupLink)
                            {
                                if(!$videoGroupLink->delete())
                                {

                                }
                            }
                        }
                    }
                    break;
                case 'file':
                    
                    if($this->request->getPost('selectedFileRemove'))
                    {
                        $selectedVideoFileLink = $this->request->getPost('selectedFileRemove');
                        foreach($selectedVideoFileLink as $videoFileId)
                        {
                            $videoFileLink = VideoFileLink::find(array(
                                "video_id = $id AND video_file_id = $videoFileId"
                            ))->getFirst();

                            if($videoFileLink)
                            {
                                if(!$videoFileLink->delete())
                                {

                                }
                            }
                        }
                    }
                    break;
                default:
                    die(print 'error');
                    return false;
                    break;
            }
            return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideo . '/edit/' . $id . '?tab=' . $tab);
        }

        $this->view->videoActorLinks = $this->modelsManager->createBuilder()
            ->from(array('videoArtistLink' => '\Backend\Modules\Video\Models\VideoArtistLink'))
            ->groupBy("videoArtistLink.artist_id")
            ->join('\Backend\Modules\Video\Models\Artist' , 'videoArtistLink.artist_id = artist.id' , 'artist')
            ->limit(Constant::ITEM_PER_PAGE_20)
            ->where('artist.artist_type = :artist_type: AND videoArtistLink.video_id = :video_id:', array('artist_type' => Artist::ACTOR , 'video_id' => $id))
            ->orderBy('videoArtistLink.artist_id')
            ->getQuery()
            ->execute();


        $this->view->videoDirectorLinks = $this->modelsManager->createBuilder()
            ->from(array('videoArtistLink' => '\Backend\Modules\Video\Models\VideoArtistLink'))
            ->groupBy("videoArtistLink.artist_id")
            ->join('\Backend\Modules\Video\Models\Artist' , 'videoArtistLink.artist_id = artist.id' , 'artist')
            ->limit(Constant::ITEM_PER_PAGE_20)
            ->where('artist.artist_type = :artist_type: AND videoArtistLink.video_id = :video_id:', array('artist_type' => Artist::DIRECTOR , 'video_id' => $id))
            ->orderBy('videoArtistLink.artist_id')
            ->getQuery()
            ->execute();


        $this->view->videoFileLinks = VideoFileLink::find(array(
            "video_id = $id"
        ));

        $this->view->videoGroupLinks = VideoGroupLink::find(array(
            "video_id = $id"
        ));

        $this->view->videoCategoryLinks = VideoCategoryLink::find(array(
            "video_id = $id"
        ));
        $this->view->tab = $tab;
        $this->view->form = $form;
        $this->view->formDescription = $formDescription;
        //$this->view->formCategoryLink = $formCategoryLink;
        $this->view->videoId = $id;
        $this->view->video = $video;
    }

    public function updateStatusAction()
    {
        $videoId = $this->request->get('video_id' , 'int');
        $status = $this->request->get('status');
        if($videoId > 0)
        {
            $video = Video::findFirstById($videoId);
            if($video)
            {
                $video->setStatus($status);
                $video->save();
                $this->flash->success("Video update success");
            }
            else
            {
                $this->flash->error($video->getMessages());
            }

            return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideo);
        }
    }

    public function deleteAction($id)
    {
        $video = Video::findFirstById($id);

        if(!$video->delete())
        {
            $this->flash->error($video->getMessages());
        }
        else
        {
            $this->flash->success("Video was deleted");
        }

        return $this->response->redirect($this->getBackendUrl() . '/' . $this->urlVideo);
    }
}
